package fi.foyt.cs.persistence.dao.user;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import fi.foyt.cs.persistence.dao.GenericDAO;
import fi.foyt.cs.persistence.domainmodel.user.User;

public class UserDAO extends GenericDAO<User> {

  public User create(String firstName, String lastName, String email, String locale, Boolean licenseAgreed) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      User user = new User();
      user.setFirstName(firstName);
      user.setLastName(lastName);
      user.setEmail(email);
      user.setLocale(locale);
      user.setLicenseAgreed(licenseAgreed);
      entityManager.persist(user);
      entityManager.getTransaction().commit();
      return user;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }
  
  public User findByEmail(String email) {
    EntityManager entityManager = getEntityManager();
    Query query = entityManager.createQuery("select u from User u where email = :email");
    query.setParameter("email", email);
    return getSingleResult(query);
  }

  public User updateLocale(User user, String locale) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      user.setLocale(locale);
      entityManager.persist(user);
      entityManager.getTransaction().commit();
      return user;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }

  public User updateLicenseAgreed(User user, Boolean licenseAgreed) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      user.setLicenseAgreed(licenseAgreed);
      entityManager.persist(user);
      entityManager.getTransaction().commit();
      return user;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }
}
